package com.JavaNet.chapter7_urlConnection;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author SwordFall
 *         create 2017-12-03 15:04.
 *         desc
 *         抽象类
 *         <p>
 *         直接子类为 HttpsURLConnection, 父类为 URLConnection
 *         使用jdk自带的 HttpURLConnection 向URL发送 POST 请求并输出响应结果
 *         参数使用流传递，并且硬编码为字符串"name=XXX"的格式
 *         https://www.baidu.com/s?wd=java
 **/
public class CallBaiduDemo {


    public static void main(String[] args) throws Exception {
        String urlPath = "http://www.baidu.com/s?wd=java";
//        String urlPath = "http://cn.bing.com/search?q=java";
        String param = "wd=" + URLEncoder.encode("硅谷", "UTF-8");



        //建立连接
        URL url = new URL(urlPath);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();


        //设置参数
        httpURLConnection.setDoOutput(true);//需要输出
        httpURLConnection.setDoInput(true);//需要输入
        httpURLConnection.setUseCaches(false);//不允许缓存
        httpURLConnection.setRequestMethod("POST");//设置POST方式连接


        //设置请求属性
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");//维持长连接
        httpURLConnection.setRequestProperty("Charset", "UTF-8");


        //连接,也可以不用明文connect,使用下面的httpURLConnection.getOutputStream()会自动connect
        httpURLConnection.connect();

        //建立输入流,向指定的URL传入参数
        DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        if (HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode()) {       //获得响应状态
            StringBuilder sb = new StringBuilder();
            String readLine;
            BufferedReader responseReader = new BufferedReader(
                    new InputStreamReader(
                            httpURLConnection.getInputStream(),
                            StandardCharsets.UTF_8
                    )
            );
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine).append("\n");
            }
            responseReader.close();
            System.out.println(sb.toString());
        }
    }


}
